package cn.fuxi2022.accounts.activity.listener;

import cn.fuxi2022.accounts.activity.service.GroupActivityService;
import cn.fuxi2022.model.empty.accounts.GroupActivity;
import cn.fuxi2022.rabbitmq.appletsPay.constants.ActivityConstants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 订单消息消费者
 * 注意：可以使用 多个线程并发或JUC，这里不演示
 */
@Slf4j
@Component
public class ActivityConsumer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private GroupActivityService groupActivityService;

    /**
     * 处理活动超时队列 监听接口
     */
    @RabbitListener(queues = ActivityConstants.GROUP_ACTIVITY_DLE_ACTIVITY_QUEUE)
    public void activityDleQueueListener(String data, Channel channel, Message message) throws IOException {
        log.info("活动超时关闭{}", data);
        // 查询活动状态
        GroupActivity groupActivity = groupActivityService.getById(data);

        // 如果已经数据库的活动关闭，这里就无需关闭，并且不再投入MQ
        if (ObjectUtils.isEmpty(groupActivity) || groupActivity.getStatus() != 1) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        // 将Date转化为LocalDateTime
        Instant instant = groupActivity.getEndTime().toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);

        // 判断当前时间 是否在 结束时间之后
        if (!LocalDateTime.now().isBefore(localDateTime)) {
            log.info("已经确认活动超时，关闭活动{}", data);
            // 已经活动结束，需要关闭活动
            groupActivityService.stopActivity(groupActivity.getId());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        // 还未到达关闭时间，再将活动重新投入队列
        rabbitTemplate.convertAndSend(ActivityConstants.GROUP_ACTIVITY_TTL_EXCHANGE, null, groupActivity.getId());

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
